<?php

namespace Trois\Di;

use App\Model\AreaModel;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use Trois\Lib\Help;

class Area
{
    use Singleton;

    private function __construct()
    {
        $this->run();
    }

    public function run(): void
    {

        $scheduler = new \Swoole\Coroutine\Scheduler();
        $scheduler->add(function () {

            $areas = [];

            $res = Help::modelInvoke(AreaModel::class, function ($model) {
                return $model->field('area_id,area_name,area_sn,area_parent_sn')->all();
            });

            foreach ($res as $re) {
                if ($re['area_parent_sn'] == 0) {
                    $re['city_list'] = [];
                    $areas[$re['area_sn']] = $re;
                }
            }

            foreach ($res as $re) {
                isset($areas[$re['area_parent_sn']]) && $areas[$re['area_parent_sn']]['city_list'][$re['area_id']] = $re;
            }

            Di::getInstance()->set('Area', $areas);

        });

        $scheduler->start();

        \Swoole\Timer::clearAll();

    }
}